const { Model, DataTypes } = require('sequelize');

module.exports = (sequelize) => {
    class User extends Model {
        static associate(models) {
            // 定义关联关系
            User.hasMany(models.RecycleOrder, {
                foreignKey: 'user_id',
                as: 'recycle_orders'
            });
            User.hasMany(models.ExchangeOrder, {
                foreignKey: 'user_id',
                as: 'exchange_orders'
            });
            User.hasMany(models.PointsRecord, {
                foreignKey: 'user_id',
                as: 'points_records'
            });
        }
    }

    User.init(
        {
            id: {
                type: DataTypes.BIGINT,
                autoIncrement: true,
                primaryKey: true,
                comment: '用户ID'
            },
            openid: {
                type: DataTypes.STRING(100),
                unique: true,
                comment: '微信openid'
            },
            nickname: {
                type: DataTypes.STRING(50),
                comment: '昵称'
            },
            avatar_url: {
                type: DataTypes.STRING(255),
                comment: '头像URL'
            },
            phone: {
                type: DataTypes.STRING(20),
                unique: true,
                comment: '手机号'
            },
            points: {
                type: DataTypes.INTEGER,
                defaultValue: 0,
                comment: '积分余额'
            }
        },
        {
            sequelize,
            modelName: 'User',
            tableName: 'users',
            timestamps: true,
            paranoid: true,
            underscored: true
        }
    );

    return User;
};